package com.example.demo.yanglq.utils;

import com.example.demo.yanglq.component.jedis.JedisExecutor;
import com.example.demo.yanglq.component.jedis.PipelineExecutor;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.Pipeline;

import java.util.List;

/**
 * @author by yanglq
 * @Classname JedisUtils
 * @Description TODO
 * @Date 2020/1/8/008 10:43
 */
@Component
public class JedisUtils {

//    @Autowired
//    private JedisPool jedisPool;
    private static final GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();

    private JedisPool jedisPool;

    public JedisUtils() {
        jedisPool = new JedisPool(poolConfig, "10.2.147.67", 6379,10000,"123456");
    }


    public <T> T execute(JedisExecutor<T> jedisExecutor) {
        try (Jedis jedis = jedisPool.getResource()) {
            return jedisExecutor.execute(jedis);
        }
    }

    public List<Object> pipeline(List<PipelineExecutor> pipelineExecutors) {
        try (Jedis jedis = jedisPool.getResource()) {
            Pipeline pipeline = jedis.pipelined();
            for (PipelineExecutor executor : pipelineExecutors) {
                executor.load(pipeline);
            }
            return pipeline.syncAndReturnAll();
        }
    }

    public Jedis getJedis() {
        return jedisPool.getResource();
    }
}
